﻿using System.Collections.Generic;
using AmazeUI.bll.Open.WeixinPay;
using Com;

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using WebCommon;
using WebCommon.StringCommand;

namespace AmazeUI.bll.Open.Weixin
{

    public class Wx
    {
        public static string AppId = Config.GetString("wxappid");
        public static string AppSecret = Config.GetString("wxappsecret");

        public string Noncestr { get; set; }

        public string TimeStamp { get; set; }


        public Wx()
        {

            this.Noncestr = WebCommon.StringCommand.RandomsAzNum.GetLun(10);
            this.TimeStamp = WebCommon.StringCommand.Static.GetTimeStamp();
        }

        /// <summary>
        ///  获取Jsapi_ticket值
        /// </summary> 
        /// <param name="accessTokenVal"></param>
        /// <returns></returns>
        public string GetValJsapi_ticket(string accessTokenVal)
        {
            JObject jo = JObject.Parse(accessTokenVal);
            var errcode = jo["errcode"].ToString();
            if (errcode == "0")
            {
                return jo["ticket"].ToString();
            }
            else
            {
                return jo["errmsg"].ToString();
            }
        }
        /// <summary>
        ///  获取access_token值
        /// </summary>
        /// <param name="accessTokenval"></param>
        /// <returns></returns>
        public string GetValAccess_token(string accessTokenval)
        {
            JObject jo = JObject.Parse(accessTokenval);
            var errcode = jo["errcode"];
            if (errcode == null)
            {
                return jo["access_token"].ToString();
            }
            else
            {
                return jo["errmsg"].ToString();
            }
        }

        /// <summary>
        /// 默认获取access_token
        /// </summary>
        /// <param name="grantType"></param>
        /// <param name="type">是否返回json</param>
        /// <returns></returns>
        public string GetAccess_token(string grantType = "client_credential")
        {
            var hp = HttpHelper.PostPage(
                   "https://api.weixin.qq.com/cgi-bin/token?grant_type=" + grantType + "&appid=" + AppId + "&secret=" +
                   AppSecret);

            return hp;
        }

        /// <summary>
        /// 获取jsapi_ticket
        /// </summary>
        /// <param name="accessToken"></param>
        /// <param name="func">返回操作</param>
        /// <returns></returns>
        public string Getjsapi_ticket(string accessToken)
        {
            var hp = HttpHelper.PostPage(
                   "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + accessToken + "&type=jsapi");
            return hp;
        }

        /// <summary>
        /// HUOQUGetSignature
        /// </summary>
        /// <returns></returns>
        public string GetSignature(string url, string jsapiTicket)
        {

            var d = new Dictionary<string, string>();
            d.Add(TypeCom.GetPropertyName<Wx>(this, this.TimeStamp).ToLower(), this.TimeStamp);
            d.Add(TypeCom.GetPropertyName<Wx>(this, this.Noncestr).ToLower(), this.Noncestr);
            d.Add("url", url);
            d.Add("jsapi_ticket", jsapiTicket);
            var obd = WebCommon.StringCommand.Static.GetOrderBy(d);
            return WebCommon.Encryption.Sha1(obd);
        }

        /// <summary>
        /// 登录接口
        /// </summary>
        /// <param name="returl">返回url</param>
        /// <param name="scope">是否弹出授权页面</param>
        /// <param name="state">备用字段</param>
        public string LoginUrl(string returl, bool scope = true, string state = "")
        {
            returl = Static.UrlEncode(returl);
            var scopestr = "";
            if (scope)
            {
                scopestr = "snsapi_userinfo";
            }
            else
            {
                scopestr = "snsapi_base";
            }

            var url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + AppId +
                      "&redirect_uri=" + returl + "&response_type=code&scope=" + scopestr + "&state=" + state + "#wechat_redirect";
            return url;

        }
        /// <summary>
        /// 通过登陆code换取Loginaccess_token
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public static WxUseraccess_token GetLoginaccess_token(string code)
        {

            var url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + AppId + "&secret=" +
                       AppSecret + "&code=" + code + "&grant_type=authorization_code";
            var p = HttpHelper.PostPage(url);

            var useraccessToken = JsonConvert.DeserializeObject<WxUseraccess_token>(p);

            return useraccessToken;
        }

        /// <summary>
        /// 获取code
        /// </summary>
        /// <param name="returl"></param>
        /// <param name="state">订单号</param>
        /// <returns></returns>
        public static string GetCodeUrl(string returl, string state)
        {
            returl = WebCommon.StringCommand.Static.UrlEncode(returl);
            var url = string.Format(
                 "https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_base&state={2}#wechat_redirect", Wx.AppId, returl, state);

            return HttpHelper.PostPage(url, "");
        }
        /// <summary>
        /// 拉取用户信息
        /// </summary>
        /// <returns></returns>
        public static WxUserInfo GetLoginUserinfo(string access_token, string openid)
        {

            var url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openid + "&lang=zh_CN";
            var p = HttpHelper.PostPage(url);
            return JsonConvert.DeserializeObject<WxUserInfo>(p);

        }
        /// <summary>
        /// 通过登陆code换取Loginaccess_token
        /// </summary>
        /// <param name="refresh_token"></param>
        /// <returns></returns>
        public WxUseraccess_token GetLoginRefreshaccess_token(string refresh_token)
        {
            var url = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=" + AppId + "&grant_type=refresh_token&refresh_token=" + refresh_token;
            var p = HttpHelper.PostPage(url);

            return JsonConvert.DeserializeObject<WxUseraccess_token>(p);

        }

        /// <summary>
        /// 检验授权凭证（access_token）是否有效
        /// </summary>
        /// <param name="openid">openid</param>
        /// <param name="access_token">access_token</param>
        /// <returns></returns>
        public static bool Isaccess_token(string openid, string access_token)
        {
            var url = "https://api.weixin.qq.com/sns/auth?access_token=" + access_token + "&openid=" + openid;
            var p = HttpHelper.PostPage(url, "");
            var jObject = JObject.Parse(p);
            return jObject["errcode"].ToString() == "0";
        }

    }
}